import time

from msg.protocol import Protocol
from common.conf import conf
from common.tools import Tool


# ffmpeg -re -i input.ps -c copy -f flv rtmp://localhost/live/stream

class Action:
    def __init__(self):
        self.c = conf
        self.t = Tool()
        self.p = Protocol()

    # msg 存的是nvr,主要是查ip port
    # invite 存的是invite报文,bye有用 按照cid chan
    # ssrc cid chan ssrc

    # ty is act or msg
    def save_msg(self, cam_id, str_recv, ip, port):
        q = {"cam_id": cam_id, "ty": "msg"}
        d = {"msg": str_recv, "ip": ip, "port": port, "time": int(time.time())}
        self.c.col.update_one(q, {"$set": d}, upsert=True)
        return

    # callid from to tag
    def on_invite_ack(self, msg):
        cid = self.t.line_by_word(msg, "Call-ID:")
        q = {"ty": "invite", "call_id": cid}
        to_s = self.t.line_by_word(msg, "To:")
        l = to_s.split("tag=")
        tag = l[1] if len(l) >= 2 else ""
        d = {"ack": msg, "to_tag": tag}
        print("ack==", q)
        self.c.col.update_one(q, {"$set": d}, upsert=True)


if __name__ == '__main__':
    ok = '''
    SIP/2.0 200 OK
Via: SIP/2.0/UDP 192.168.0.101:5061;rport=5061;branch=ODSCaaOW827pgJNI
From: <sip:34020000002000000001@192.168.0.101>;tag=3195160060
To: <sip:34020000001320000001@192.168.0.102:5060>;tag=198456547
Call-ID: 00999901
CSeq: 20 INVITE
Contact: <sip:34020000001320000001@192.168.0.102:5060>
Content-Type: application/SDP
User-Agent: Embedded Net DVR/NVR/DVS
Content-Length:   239

v=0
o=34020000001110009999 0 0 IN IP4 192.168.0.102
s=Play
c=IN IP4 192.168.0.102
t=0 0
m=video 62000 RTP/AVP 96
a=sendonly
a=rtpmap:96 PS/90000
a=username:34020000001110009999
a=password:12345678
a=filesize:0
y=0000999901
f=
    '''
    a = Action()
    # cam_id = "34020000001110000001"
    a.save_invite_ok(ok)
